
// 导入数据库操作模块
const db = require('../db/index')
// 导入处理路径的 path 核心模块
const path = require("path");
const fs = require('fs');



exports.editRecommend = (req, res) => {        
  const defaultImage = [
     'uploads/recommend/default-站酷.ico',
     'uploads/recommend/default-ui中国.ico', 
     'uploads/recommend/default-dirbbble.png',
     'uploads/recommend/default-优设.ico',
     'uploads/recommend/default-figma.ico',
     'uploads/recommend/default-百度.ico',
  ]
  const id = req.body.id;
  const sql = `SELECT logoImg FROM zc_recommend WHERE id = ?`
  db.query(sql, [id], (err, results) => {
      if (err) return res.cc(err);
      if (results.length > 0) {
          const oldImagePath = results[0].logoImg;
          console.log(oldImagePath)
          if (req.file && !defaultImage.includes(oldImagePath) && fs.existsSync(oldImagePath)) {
              fs.unlink(oldImagePath, (err) => {
                  if (err) return res.cc(err);
                  console.log("图片已删除")
              });
          }
          let imagePath;
          if(req.body.logoImg){
              imagePath = req.body.logoImg;
          }else if(req.file){
              imagePath = path.join('uploads/recommend', req.file.filename);
          }else{
              imagePath = oldImagePath;
          }
          const recommendInfo = {
              // 标题、内容、状态、所属的分类Id
              ...req.body,
              // logo在服务器端的存放路径
              logoImg : imagePath
          };
          const sql = `update zc_recommend set ? where id = ?`;
          db.query(sql, [recommendInfo, req.body.id], (err, results) => {
              if (err) return res.cc(err);
              if (results.affectedRows !== 1) return res.cc("更新失败！");
              res.cc("更新成功！", 0);
          });
      }
  });
}



// 获取推荐的函数
exports.getRecommend = (req, res) => {

const userId = req.params.userId;
// const sql = 'select * from zc_recommend WHERE user_id = ?'
const sql = 'SELECT * FROM zc_recommend WHERE user_id = ? ORDER BY sort_order'
db.query(sql, [userId], (err, results) => {
  // 1. 执行 SQL 语句失败
  if (err) return res.cc(err)

  // 2. 执行 SQL 语句成功
  res.send({
    status: 0,
    message: '获取成功！',
    data: results,
  })
})
}

// 拖拽推荐的函数
exports.saveSortOrder = (req, res) => {
    try {
        const userId = req.params.userId;
        const updates = req.body;
        // const updates = Array.isArray(req.body) ? req.body : [];


        console.log('请求体:', req.body); // 打印请求体

        // 将对象转换为数组
        const updatesArray = Object.keys(updates).map(key => ({
            id: updates[key]['id'],
            sort_order: updates[key]['sort_order']
        }));

        // 检查更新是否为空
        if (updatesArray.length === 0) {
            return res.status(400).send({ message: '请求体格式错误，updates 为空' });
        }

        const sql = 'UPDATE zc_recommend SET sort_order = ? WHERE id = ? AND user_id = ?';

        const updatePromises = updatesArray.map(update => {
            return new Promise((resolve, reject) => {
                console.log('待更新的项:', update);
                console.log('userId:', userId);
                console.log('参数:', [update.sort_order, update.id, userId]);

                db.query(sql, [update.sort_order, update.id, userId], (err, results) => {
                    if (err) {
                        console.error('SQL 执行错误:', err);
                        return reject(err);
                    }

                    console.log('更新结果:', results);
                    if (results.affectedRows === 0) {
                        console.warn(`没有找到用户ID为${userId}，推荐项ID为${update.id}的记录`);
                    }

                    resolve(results);
                });
            });
        });

        Promise.all(updatePromises)
            .then(() => {
                res.send({
                    status: 0,
                    message: '排序更新成功！',
                });
            })
            .catch(err => {
                console.error('更新失败', err);
                res.cc(err);
            });
    } catch (error) {
        console.error('处理请求时发生错误:', error);
        res.status(500).send({ message: '服务器内部错误' });
    }
}


  

// // 编辑推荐的处理函数1.0
 
// exports.editRecommend = (req, res) => {        
//   const defaultImage = [
//      'uploads/recommend/default-站酷.ico',
//      'uploads/recommend/default-ui中国.ico', 
//      'uploads/recommend/default-dirbbble.png',
//      'uploads/recommend/default-优设.ico',
//      'uploads/recommend/default-figma.ico',
//      'uploads/recommend/default-百度.ico',
//   ]
//   const id = req.body.id;
//   const sql = `SELECT logoImg FROM zc_recommend WHERE id = ?`
//   db.query(sql, [id], (err, results) => {
//       if (err) return res.cc(err);
//       if (results.length > 0) {
//           const oldImagePath = results[0].logoImg;
//           console.log(oldImagePath)
//           if (req.file && !defaultImage.includes(oldImagePath) && fs.existsSync(oldImagePath)) {
//               fs.unlink(oldImagePath, (err) => {
//                   if (err) return res.cc(err);
//                   console.log("图片已删除")
//               });
//           }
//           //这个有问题 '/uploads/recommend'
//           const imagePath = req.file ? path.join('uploads/recommend', req.file.filename) : oldImagePath;
//           const recommendInfo = {
//               // 标题、内容、状态、所属的分类Id
//               ...req.body,
//               // 文章封面在服务器端的存放路径
//               logoImg : imagePath
//           };
//           const sql = `update zc_recommend set ? where id = ?`;
//           db.query(sql, [recommendInfo, req.body.id], (err, results) => {
//               if (err) return res.cc(err);
//               if (results.affectedRows !== 1) return res.cc("更新失败！");
//               res.cc("更新成功！", 0);
//           });
//       }
//   });
// }